package com.heima.gateway.app.filter;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.heima.gateway.app.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.core.config.Order;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author : lenovo
 * @date: 2024/12/30 15:12
 */
@Component
@Order(-1) //最先执行
@Slf4j
public class AuthFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取请求路径   http://12.12.131.31:22/api/saa  -> api/saa
        String path = request.getURI().getPath();
        log.info("获取到请求路径：{}",path);
        if(path.contains("/login")){
            //登录请求放行
            return chain.filter(exchange);
        }
        //获取token
        String token = request.getHeaders().getFirst("token");
        //若没有token返回401
        if(StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //有token则解析token
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        //校验token是否过期
        int flag = AppJwtUtil.verifyToken(claimsBody);
        if(flag == 1 || flag == 2){
            //过期则返回401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        return chain.filter(exchange);
    }
}
